﻿using Bookify.Application.Abstractions.Messaging;
using Bookify.Domain.Abstractions;
using MediatR;
using Microsoft.Extensions.Logging;
using Serilog.Context;

namespace Bookify.Application.Abstractions.Behaviors
{
    public class LoggingBehavior<TRequest, TResponse>
        : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IBaseCommand
        where TResponse : Result
    {
        private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
        public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
        {
            _logger = logger;
        }


        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            var requestName = request.GetType().Name;

            try
            {
                _logger.LogInformation("Request {RequestName} 执行中", requestName);

                TResponse result = await next();

                if (result.IsSuccess)
                { 
                    _logger.LogInformation("Request {RequestName} 执行成功", requestName);
                }
                else
                {
                    using (LogContext.PushProperty("Errors", result.Error,true))
                    {
                        _logger.LogError("Request {RequestName} 执行失败", requestName);
                    }
                }
                return result;
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Request {RequestName} 执行失败", requestName);
                throw;
            }
        }
    }
}
